import { BUNDLE_TYPE_ENUM } from "../../base/EnumIndex";
import { Tools } from "../../common/Tools";
import TouchScale from "../../item/Common/TouchScale";
import { AudioManager1 } from "../../manager/AudioManager1";
import { UIManager } from "../../manager/UIManager";
import LvItem from "../../LvItem";
import LevelPre_23 from "./LevelPre_23";

import Level_23_Base from "./Level_23_Base";

const { ccclass, property } = cc._decorator;
let ANSWER: Array<Array<[string, boolean, string, string]>> = [];
let QUESION = [];
let WRONG_NUM = 3;

enum GAME_STATE {
    RUNNING, WIN, FAIL
}
@ccclass
export default class Level_23_16 extends Level_23_Base {

    @property(cc.Node)
    huaping: cc.Node = null;

    @property(cc.Node)
    renwu: cc.Node = null;

    autoMove_X: number;
    autoMove_Y: number;


    @property(cc.Node)
    npcTalk2: cc.Node = null;


    @property(sp.Skeleton)
    npcSpine2: sp.Skeleton = null;


    NpcAudioId2: number = null

    /** 更新选择 */
    gengxinxuanze = false;

    /** 道士离开 */
    daoshizou = false;

    start(): void {
        this.levelPre = cc.find("Canvas").getComponentInChildren(LevelPre_23);
        ANSWER = this.levelPre.interJson.answer;
        QUESION = this.levelPre.interJson.questions;

        this.getCanvasNodeForName("goalItem").addComponent(cc.Widget)
        this.getCanvasNodeForName("goalItem").getComponent(cc.Widget).alignMode = cc.Widget.AlignMode.ALWAYS;
        this.getCanvasNodeForName("goalItem").getComponent(cc.Widget).target = cc.find('Canvas')
        this.getCanvasNodeForName("goalItem").getComponent(cc.Widget).isAlignRight = true;
        this.getCanvasNodeForName("goalItem").getComponent(cc.Widget).isAlignTop = true;
        this.getCanvasNodeForName("goalItem").getComponent(cc.Widget).right = 30;
        this.getCanvasNodeForName("goalItem").active = false;


        this.levelPre.node.on(cc.Node.EventType.TOUCH_START, this.npcTalkEnd, this)


        // 适配
        let widthScale = this.levelPre.maskNode.width / this.levelPre.huaNode.width;
        let heightScale = this.levelPre.maskNode.height / this.levelPre.huaNode.height;
        this.levelPre.huaNode.scale = Math.min(widthScale, heightScale);

        if (this.levelPre.huaNode.getComponent(TouchScale)) {
            this.levelPre.huaNode.getComponent(TouchScale).maskNode = this.levelPre.maskNode;
        }

        let isAutoAnswerActive = Tools.getStorage('setAutoAnswerActive')
        if (isAutoAnswerActive && isAutoAnswerActive != "false") {
            this.autoAnswer = true;
        } else {
            this.autoAnswer = false;
        }

        let isAnswerRightActive = Tools.getStorage('setAnswerRightActive')
        if (isAnswerRightActive && isAnswerRightActive != "false") {
            this.answerRight = true;
        } else {
            this.answerRight = false;
        }

    }

    async startGame() {
        this.isSelect = false;
        cc.log("当前第" + this.levelPre.progress + "题")
        this.gengxinxuanze = false
        UIManager.ins.enabledGameClick(true);
        // UIManager.ins.enabledGameClick(false);
        this.npcTalk.active = true;
        this.npcTalk.getComponent(LvItem).setLabString(QUESION[this.levelPre.progress][0]);
        this.npcSpine.setAnimation(0, "shuohua", true);
        this.talkAnim();
        this.NpcAudioId = await AudioManager1.playAudio((QUESION[this.levelPre.progress][0]), 1, BUNDLE_TYPE_ENUM.LEVEL);
        cc.Tween.stopAllByTarget(this.npcTalk);
        let audioTime = cc.audioEngine.getDuration(this.NpcAudioId);
        cc.tween(this.npcTalk).delay(audioTime).call(() => this.npc2()).start();


    }

    async npc2() {
        this.npcSpine.setAnimation(0, "daiji", true);

        this.npcTalk2.active = true;
        if (this.levelPre.progress == 2) {
            this.npcTalk2.getComponent(LvItem).setLabString("你知道自己为什么会在这里吗");
        } else {
            this.npcTalk2.getComponent(LvItem).setLabString(QUESION[this.levelPre.progress][1]);
        }
        this.npcSpine2.setAnimation(0, "daiji_shuohua", true);
        this.talkAnim();
        this.NpcAudioId2 = await AudioManager1.playAudio((QUESION[this.levelPre.progress][1]), 1, BUNDLE_TYPE_ENUM.LEVEL);
        cc.Tween.stopAllByTarget(this.npcTalk2);
        let audioTime2 = cc.audioEngine.getDuration(this.NpcAudioId2);
        cc.tween(this.npcTalk2).delay(audioTime2).call(() => this.npcTalkEnd()).start();
    }

    npcTalkEnd() {
        console.log('更新选择', this.gengxinxuanze);

        if (this.gengxinxuanze) {
            return;
        }
        this.gengxinxuanze = true
        this.levelPre.content.active = true;

        if (this.levelPre.progress >= 6) {
            this.huaping.on(cc.Node.EventType.TOUCH_START, this.touchMoveBack1, this)
            this.huaping.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack1, this)
            this.huaping.on(cc.Node.EventType.TOUCH_END, this.touchEndBack1, this)

            this.renwu.on(cc.Node.EventType.TOUCH_START, this.touchMoveBack2, this)
            this.renwu.on(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack2, this)
            this.renwu.on(cc.Node.EventType.TOUCH_END, this.touchEndBack2, this)


            this.gN("qCon").active = false;
        } else {
            this.updateOption();
        }

        this.npcTalk2.active = true;
        this.npcTalk.active = true;
        this.npcTalk.getComponent(LvItem).setLabString(QUESION[this.levelPre.progress][0]);
        if (this.levelPre.progress == 2) {
            this.npcTalk2.getComponent(LvItem).setLabString("你知道自己为什么会在这里吗");
        } else {
            this.npcTalk2.getComponent(LvItem).setLabString(QUESION[this.levelPre.progress][1]);
        }

        cc.Tween.stopAllByTarget(this.npcTalk);
        cc.Tween.stopAllByTarget(this.npcTalk2);

        this.npcSpine.setAnimation(0, "daiji", true);
        this.npcSpine2.setAnimation(0, "daiji", true);

        AudioManager1.stopAudio(this.NpcAudioId)
        AudioManager1.stopAudio(this.NpcAudioId2)

        UIManager.ins.enabledGameClick(true);
    }

    /** 通过名字获取节点 */
    getCanvasNodeForName(name: string) {
        const canvasNode = cc.find('Canvas');
        // cc.log(name, canvasNode)
        if (!canvasNode) return null;
        let nodeArr = canvasNode.getComponentsInChildren(LvItem);
        for (let i = 0; i < nodeArr.length; i++) {
            if (nodeArr[i].node.name == name) {
                return nodeArr[i].node;
            }
        }
        let node = this.getCanvasChildForName(name);
        if (node) {
            return node;
        }
        return null;
    };

    /** 通过名字 获取子节点下的节点 */
    getCanvasChildForName(name: string, parentNode?: cc.Node): cc.Node {
        if (!name) { return null; }
        const canvasNode = cc.find('Canvas');
        parentNode = parentNode || canvasNode;

        for (let i = 0; i < parentNode.children.length; i++) {
            const node = parentNode.children[i];
            if (node.name == name) {
                return node;
            }
            if (node.children.length > 0) {
                let temp = this.getCanvasChildForName(name, node);
                if (temp) {
                    return temp;
                }
            }
        }
        return null;
    };

    protected onDisable(): void {
        this.huaping.off(cc.Node.EventType.TOUCH_START, this.touchMoveBack1, this)
        this.huaping.off(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack1, this)
        this.huaping.off(cc.Node.EventType.TOUCH_END, this.touchEndBack1, this)


        this.renwu.off(cc.Node.EventType.TOUCH_START, this.touchMoveBack2, this)
        this.renwu.off(cc.Node.EventType.TOUCH_MOVE, this.touchMoveBack2, this)
        this.renwu.off(cc.Node.EventType.TOUCH_END, this.touchEndBack2, this)

        this.node.off(cc.Node.EventType.TOUCH_END, this.npcTalkEnd, this)
    }
    touchEndBack1() {
        let isZayun = this.isNodeInterNode(this.huaping, this.renwu)
        this.huaping.setSiblingIndex(3)
        if (isZayun) {
            this.npcTalk.active = false;
            this.npcTalk2.active = false;
            this.huaping.active = false;
            this.gN("npcSayNode").active = false;
            this.gN("npc2SayNode").active = false;

            this.gN("qCon").active = false;

            this.daoshizou = true;
            this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("winGame1").interTween);
        } else {

            cc.tween(this.huaping).to(0.1, { position: cc.v3(-425.564, 463.442) }).start();
        }
    }
    touchMoveBack1(touches: cc.Event.EventTouch) {
        let pos = Tools.getToNodePosForWorld(touches.getLocation(), this.huaping.parent);
        this.huaping.setPosition(pos);
        this.huaping.setSiblingIndex(15)

        let tempPos = Tools.getToNodePosForNode(this.huaping, this.levelPre.huaNode.parent);
        let tempLen = 50;
        if (touches.getDelta().x > 0 && tempPos.x >= this.levelPre.huaNode.parent.width / 2 - this.huaping.width / 2 - tempLen) {
            this.autoMove_X = -800;
        } else if (touches.getDelta().x < 0 && tempPos.x <= -this.levelPre.huaNode.parent.width / 2 + this.huaping.width / 2 + tempLen) {
            this.autoMove_X = 800;
        } else if (touches.getDelta().y > 0 && tempPos.y >= this.levelPre.huaNode.parent.height / 2 - this.huaping.height / 2 - tempLen) {
            this.autoMove_Y = -800;
        } else if (touches.getDelta().y < 0 && tempPos.y <= -this.levelPre.huaNode.parent.height / 2 + this.huaping.height / 2 + tempLen) {
            this.autoMove_Y = 800;
        } else {
            this.autoMove_X = 0;
            this.autoMove_Y = 0;
        }
    }

    touchEndBack2() {
        if (!this.daoshizou) {
            return;
        }
        this.levelPre.progress++;
        this.renwu.setSiblingIndex(8)
        let isZayun1 = this.isNodeInterNode(this.renwu, this.gN("左门"))
        let isZayun2 = this.isNodeInterNode(this.renwu, this.gN("右门"))
        if (isZayun1) {
            this.npcTalk.active = false;
            this.npcTalk2.active = false;
            this.renwu.active = false;
            this.gN("背影").active = true;
            UIManager.ins.enabledGameClick(false);

            this.gN("气泡1").getComponent(cc.Label).string = ""; // 清空文本内容
            this.gN("气泡2").getComponent(cc.Label).string = ""; // 清空文本内容
            this.typingFinish = false;
            this.typewriterEffect();

            this.scheduleOnce(() => {
                if (this.daoshizou) {
                    this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("winGame").interTween);
                } else {
                    this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("overGame1").interTween);
                }
            }, 2)
        } else if (isZayun2) {
            this.npcTalk.active = false;
            this.npcTalk2.active = false;
            this.renwu.active = false;
            this.gN("走路").active = true;
            UIManager.ins.enabledGameClick(false);
            cc.tween(this.gN("右走路")).by(1, { x: 800 }).start();
            this.scheduleOnce(() => {
                this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("overGame2").interTween);
            }, 2)
        } else {

            cc.tween(this.renwu).to(0.1, { position: cc.v3(1, 25) }).start();
        }
    }
    touchMoveBack2(touches: cc.Event.EventTouch) {
        if (!this.daoshizou) {
            return;
        }
        let pos = Tools.getToNodePosForWorld(touches.getLocation(), this.renwu.parent);
        this.renwu.setPosition(pos);
        this.renwu.setSiblingIndex(15)

        let tempPos = Tools.getToNodePosForNode(this.renwu, this.levelPre.huaNode.parent);
        let tempLen = 50;
        if (touches.getDelta().x > 0 && tempPos.x >= this.levelPre.huaNode.parent.width / 2 - this.renwu.width / 2 - tempLen) {
            this.autoMove_X = -800;
        } else if (touches.getDelta().x < 0 && tempPos.x <= -this.levelPre.huaNode.parent.width / 2 + this.renwu.width / 2 + tempLen) {
            this.autoMove_X = 800;
        } else if (touches.getDelta().y > 0 && tempPos.y >= this.levelPre.huaNode.parent.height / 2 - this.renwu.height / 2 - tempLen) {
            this.autoMove_Y = -800;
        } else if (touches.getDelta().y < 0 && tempPos.y <= -this.levelPre.huaNode.parent.height / 2 + this.renwu.height / 2 + tempLen) {
            this.autoMove_Y = 800;
        } else {
            this.autoMove_X = 0;
            this.autoMove_Y = 0;
        }
    }
    gN(NodeName: string) {
        return this.levelPre.getNodeForName(NodeName);
    }

    /** 检测答案对错 */
    async checkAnswer(progress: number, answer: number) {
        this.npcTalk.active = false;
        this.npcTalk2.active = false;
        AudioManager1.stopAudio(this.NpcAudioId)
        AudioManager1.stopAudio(this.NpcAudioId2)
        let questions = ANSWER[progress];
        let txt = questions[answer][3] || questions[answer][0];
        let isRight = questions[answer][1];
        if (this.autoAnswer || this.answerRight) {
            isRight = true;
        }
        let audio = questions[answer][2];
        let audioUrl = txt;

        this.mainTalk.active = true;
        this.mainTalk.getComponent(LvItem).setLabString(txt);
        cc.Tween.stopAllByTarget(this.mainTalk);
        this.mainSpine.setAnimation(0, "shuohua", true);

        this.MainAudioId = await AudioManager1.playAudio(audioUrl, 1, BUNDLE_TYPE_ENUM.LEVEL);
        let audioTime = cc.audioEngine.getDuration(this.MainAudioId);

        let time = 2
        cc.tween(this.node).delay(audioTime).call(() => {
            if (!isRight) this.wrongNum += 1;
            this.levelPre.progress++;
            this.updateGameState();

            this.mainSpine.setAnimation(0, "daiji", true);
            this.npcTalk.active = false;
            this.npcTalk2.active = false;
            this.mainTalk.active = false

            if (audio == ".1" || this.autoAnswer || this.answerRight) {
                this.rightAnim();
            } else {
                if (audio == ".2") {
                    this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("overGame1").interTween);
                } else if (audio == ".3") {
                    this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("overGame2").interTween);
                }
                this.subHp();
                this.wrongAnim();
                this.getCanvasNodeForName("goalItem").active = false;
                // this.updateGame();
            }
        }).delay(time).call(() => {
            if (isRight) {
                this.updateGame();
            }
        }).start();
    }
    /** 游戏状态 */
    updateGameState() {
        if (this.wrongNum >= WRONG_NUM) {
            this.gameState = GAME_STATE.FAIL;
        } else if (this.levelPre.progress === ANSWER.length) {
            this.gameState = GAME_STATE.WIN;
        } else {
            this.gameState = GAME_STATE.RUNNING;
        }
    }
    updateGame() {
        switch (this.gameState) {
            case GAME_STATE.RUNNING:
                this.resetAnim();
                this.startGame()
                break;
            case GAME_STATE.WIN:
                this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("winGame").interTween);
                break;
            case GAME_STATE.FAIL:
                // this.levelPre.runNodeTween(this.node, this.levelPre.getInterTwForName("overGame").interTween);
                break;
            default:
                break;
        }
    }
    /** 点击选项后 处理 */
    finish(finishStr: any) {
        if (typeof finishStr != "string") {
            return;
        }

        if (finishStr.includes("ans")) {
            this.isSelect = true;
            let progress = Number(finishStr.split("_")[2]);
            let answer = Number(finishStr.split("_")[3]);
            this.levelPre.playQuestionAnim(false);
            this.checkAnswer(progress, answer - 1);
        } else if (finishStr === "initGame") {
            this.initGame();
            // this.getCanvasNodeForName("goalItem").active = true;
        } else if (finishStr === "reviveGame") {
            if (this.huaping.active) {
                this.levelPre.progress--;
                this.wrongNum--;
                this.resetAnim();
                this.startGame();
            } else {
                this.resetAnim();
                cc.tween(this.renwu).to(0.1, { position: cc.v3(1, 25) }).start();
                this.renwu.active = true;
                this.gN("走路").active = false;
                UIManager.ins.enabledGameClick(true);
                cc.tween(this.gN("右走路")).by(0.1, { x: -800 }).start();
                cc.tween(this.gN("dashi")).by(0.1, { x: -400 }).start();
            }
        }
    }

    getDelayTime(isRight: boolean) {
        return isRight ? 2 : 2;
    }
    resetAnim() {
        if (this.npcSpine.animation != "daiji") this.npcSpine.setAnimation(0, "daiji", true);
    }
    talkAnim() {

    }
    rightAnim() {
        AudioManager1.playAudio("xuandui", 1, BUNDLE_TYPE_ENUM.GAME);
    }
    wrongAnim() {
        this.scheduleOnce(() => {
            this.npcSpine.addAnimation(0, "daiji", true);
        }, 1);
    }

    /** 判断两个节点是否相交 */
    isNodeInterNode(node1: cc.Node, node2: cc.Node) {
        if (!node1.active || !node2.active) { return false; };
        let wordPos1 = Tools.getToWorldPosAR(node1);
        let worldScale1 = this.getWorldScale(node1.scale, node1);
        let wordPos2 = Tools.getToWorldPosAR(node2);
        let worldScale2 = this.getWorldScale(node2.scale, node2);
        let size1 = cc.size(node1.width * worldScale1, node1.height * worldScale1);
        let size2 = cc.size(node2.width * worldScale2, node2.height * worldScale2);

        let rect1 = new cc.Rect(wordPos1.x - size1.width / 2, wordPos1.y - size1.height / 2, size1.width, size1.height);
        let rect2 = new cc.Rect(wordPos2.x - size2.width / 2, wordPos2.y - size2.height / 2, size2.width, size2.height);
        if (cc.Intersection.rectRect(rect1, rect2)) {
            return true;
        }
        return false;
    };
    /** 获取世界Scale */
    getWorldScale(tempScale: number = 1, node: cc.Node) {
        if (node.parent) {
            return this.getWorldScale(tempScale * node.parent.scale, node.parent);
        }
        return tempScale;
    };


    typewriterEffect() {
        this.schedule(this.typeNextCharacter, 1 / this.typingSpeed);
    }

    typeNextCharacter() {
        if (this.typingFinish) {
            this.unschedule(this.typeNextCharacter);
            return;
        }

        // 添加下一个字符到文本内容
        this.gN("气泡1").getComponent(cc.Label).string += this.content[this.currentIndex];
        this.gN("气泡2").getComponent(cc.Label).string += this.content[this.currentIndex];

        // 更新当前索引
        this.currentIndex++;

        // 判断是否打字完成
        if (this.currentIndex >= this.content.length) {
            this.typingFinish = true;
        }
    }

    @property({ displayName: "打字速度" })
    typingSpeed: number = 3; // 打字速度，每秒多少个字符

    @property({ displayName: "文本内容" })
    content: string = ""; // 完整的文本内容

    private currentIndex: number = 0; // 当前打字到的索引
    private typingFinish: boolean = false; // 打字是否完成


}